/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.inspur.edp.web.designschema.webservice;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.inspur.edp.formserver.viewmodel.GspViewModel;
import com.inspur.edp.web.common.customexception.WebCustomException;
import com.inspur.edp.web.common.logger.WebLogger;
import com.inspur.edp.web.common.serialize.SerializeUtility;
import com.inspur.edp.web.designschema.api.webservice.DesignSchemaWebService;
import com.inspur.edp.web.designschema.elements.Schema;
import com.inspur.edp.web.designschema.generator.SchemaBuilder;

/**
 * description:
 *
 * @author Noah Guo
 * @date 2021/01/15
 */
public class DesignSchemaWebServiceImpl implements DesignSchemaWebService {
    @Override
    public String CreateDesignSchema(JSONObject content) {
        try {
            String scene = "";
            boolean isRuntime = false;
            JSONObject viewObject = content;

            String viewObjectKey = "viewObject";
            if (content.get(viewObjectKey) != null) {
                // vo dto 又包了一层，放在viewObject属性下，为了传递额外的参数
                viewObject = content.getJSONObject(viewObjectKey);
                String sceneKey = "scene";
                if (content.containsKey(sceneKey)) {
                    scene = content.getString(sceneKey);
                }
                String isRuntimeKey = "isRuntime";
                if (content.containsKey(isRuntimeKey)) {
                    isRuntime = content.getBoolean(isRuntimeKey);
                }
            }

            String viewObjectContent = SerializeUtility.getInstance().serialize(viewObject);
            GspViewModel vm = SerializeUtility.getInstance().deserialize(viewObjectContent, GspViewModel.class);

            SchemaBuilder schemaBuilder = new SchemaBuilder();

            Schema schema = schemaBuilder.buildWithScene(vm, scene, isRuntime);

            return SerializeUtility.getInstance().valueToJson(schema, PropertyNamingStrategy.LOWER_CAMEL_CASE).toString();
        } catch (WebCustomException e) {
            WebLogger.Instance.error(e, DesignSchemaWebServiceImpl.class.getName());
            throw e;
        }
    }

    @Override
    public String CreateDesignSchemaByScene(JSONObject content) {
        return null;
    }

}

